// models/order.js
const { Model, DataTypes } = require('sequelize');
const { sequelize } = require('../config/mysql_config');

class Order extends Model {}
Order.init(
    {
        id: { type: DataTypes.INTEGER.UNSIGNED, autoIncrement: true, primaryKey: true },
        userId: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: false,
            comment: '下单用户ID',
        },
        advisorId: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: false,
            comment: '顾问ID',
        },
        serviceId: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: false,
            comment: '购买的服务ID',
        },
        serviceType: {
          type: DataTypes.TINYINT.UNSIGNED,
            allowNull: false,
            comment: '服务类型'
        },
        serviceName: {
            type: DataTypes.STRING(30),
            allowNull: true,
            comment: "服务名称",
        },
        status: {
            type: DataTypes.STRING(10),
            allowNull: false,
            defaultValue: 'pending',
            comment: '订单状态',
        },
        isRush: {
            type: DataTypes.TINYINT,
            allowNull: false,
            defaultValue: 0,
            comment: '是否加急(1小时优先)',
        },
        isRushCanceled: {
            type: DataTypes.TINYINT,
            allowNull: false,
            defaultValue: 0,
            comment: '加急是否取消',
        },
        rushPrice: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: false,
            defaultValue: 0,
            comment: '加急费用(未加急为0)',
        },
        servicePrice: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: false,
            comment: '服务价格(金币)',
        },
        totalPrice: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: false,
            comment: '总价=服务价+加急费',
        },
        paidAt: {
            field: 'paidAt_ms',
            type: DataTypes.BIGINT.UNSIGNED,
            allowNull: true,
            comment: '支付时间(ms since epoch)',
            get() {
                const v = this.getDataValue('paidAt');
                return v == null ? null : new Date(Number(v)).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' });     // 读 -> Date
            },
            set(val) {
                if (val == null) return this.setDataValue('paidAt', null);
                if (val instanceof Date) return this.setDataValue('paidAt', val.getTime()); // 写 Date
                if (typeof val === 'number') return this.setDataValue('paidAt', val);       // 已是 ms
                if (typeof val === 'string') return this.setDataValue('paidAt', Date.parse(val)); // 解析
            }
        },
        repliedAt: {
            field: 'repliedAt_ms',
            type: DataTypes.BIGINT.UNSIGNED,
            allowNull: true,
            comment: '顾问首次回复时间(ms)',
            get() { const v = this.getDataValue('repliedAt'); return v==null?null:new Date(Number(v)).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' }); },
            set(val){ this.setDataValue('repliedAt', val==null?null:(val instanceof Date?val.getTime():Number(val))); }
        },
        completedAt: {
            field: 'completedAt_ms',
            type: DataTypes.BIGINT.UNSIGNED,
            allowNull: true,
            comment: '完成时间(ms)',
            get() { const v = this.getDataValue('completedAt'); return v==null?null:new Date(Number(v)).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' }) ; },
            set(val){ this.setDataValue('completedAt', val==null?null:(val instanceof Date?val.getTime():Number(val))); }
        },
        rushDeadlineAt: {
            field: 'rushDeadlineAt_ms',
            type: DataTypes.BIGINT.UNSIGNED,
            allowNull: true,
            comment: '加急截止(ms)',
            get() { const v = this.getDataValue('rushDeadlineAt'); return v==null?null:new Date(Number(v)).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' }) ; },
            set(val){ this.setDataValue('rushDeadlineAt', val==null?null:(val instanceof Date?val.getTime():Number(val))); }
        },
        expireAt: {
            field: 'expireAt_ms',
            type: DataTypes.BIGINT.UNSIGNED,
            allowNull: false,
            comment: '自然过期(ms)',
            get() { const v = this.getDataValue('expireAt'); return v==null?null:new Date(Number(v)).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' }) ; },
            set(val){ this.setDataValue('expireAt', val instanceof Date?val.getTime():Number(val)); }
        },

        generalSituation: { type: DataTypes.TEXT, allowNull: true },
        specificQuestion: { type: DataTypes.STRING(200), allowNull: true },

        attachmentsCnt: {
            type: DataTypes.SMALLINT.UNSIGNED,
            allowNull: false,
            defaultValue: 0,
            comment: '附件数量统计',
        }
    },
    {
        sequelize,
        modelName: 'Order',
        tableName: 'orders',
        underscored: true, //驼峰转蛇形
        timestamps: true,
        comment: '订单主表',
        indexes: [
            { name: 'idx_user_time', fields: ['user_id', 'created_at'] },
            { name: 'idx_advisor_status_time', fields: ['advisor_id', 'status', 'created_at'] },
        ],
    }
);


class OrderReply extends Model {}
OrderReply.init(
    {
        id: { type: DataTypes.INTEGER.UNSIGNED, autoIncrement: true, primaryKey: true },
        orderId: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: false,
            comment: '订单ID',
        },
        advisorId: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: false,
            comment: '回复人(顾问)ID',
        },
        contentType: {
            type: DataTypes.ENUM('text', 'audio'),
            allowNull: false,
            defaultValue: 'text',
            comment: '回复类型',
        },
        contentText: { type: DataTypes.TEXT('medium'), allowNull: true, comment: '文本回复' },
        audioUrl: { type: DataTypes.STRING(500), allowNull: true, comment: '音频URL' },
        textCnt: {type: DataTypes.INTEGER.UNSIGNED, allowNull: true, comment: '文本字数'}
    },
    {
        sequelize,
        modelName: 'OrderReply',
        tableName: 'order_replies',
        underscored: true,
        timestamps: true,
        comment: '订单回复记录',
        indexes: [
            { name: 'idx_order', fields: ['order_id'] },
            { name: 'idx_advisor_time', fields: ['advisor_id', 'created_at'] },
        ],
    }
);


class OrderAttachment extends Model {}

OrderAttachment.init(
    {
        id: { type: DataTypes.INTEGER.UNSIGNED, autoIncrement: true, primaryKey: true },
        orderId: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: false,
            comment: '订单ID',
        },
        uploaderId: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: false,
            comment: '上传者(通常是用户)',
        },
        fileUrl: {
            type: DataTypes.STRING(500),
            allowNull: false,
            comment: '文件地址',
        },
        fileType: {
            type: DataTypes.STRING(50),
            allowNull: false,
            comment: 'MIME或自定义类型',
        },
    },
    {
        sequelize,
        modelName: 'OrderAttachment',
        tableName: 'order_attachments',
        underscored: true,
        timestamps: true,
        comment: '订单附件',
        indexes: [{ name: 'idx_order', fields: ['order_id'] }],
    }
);


class OrderStatusLog extends Model {}

OrderStatusLog.init(
    {
        id: { type: DataTypes.INTEGER.UNSIGNED, autoIncrement: true, primaryKey: true },
        orderId: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: false,
        },
        fromStatus: {
            type: DataTypes.STRING(10),
            allowNull: true,
        },
        toStatus: {
            type: DataTypes.STRING(10),
            allowNull: false,
        },
        reasonCode: {
            type: DataTypes.STRING(64),
            allowNull: false,
            comment: 'USER_PAY/ADVISOR_REPLY/RUSH_TIMEOUT_REFUND/NORMAL_TIMEOUT 等',
        }
    },
    {
        sequelize,
        modelName: 'OrderStatusLog',
        tableName: 'order_status_logs',
        underscored: true,
        timestamps: true,
        comment: '订单状态流水',
        indexes: [{ name: 'idx_order_time', fields: ['order_id', 'created_at'] }],
    }
);

module.exports = {
    Order,
    OrderReply,
    OrderAttachment,
    OrderStatusLog
}